﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Phoenix.Xna.Framework.Collections;
using Phoenix.Xna.Framework.Serialization;
using Microsoft.Xna.Framework.Graphics;

namespace Phoenix.Xna.Framework.Graphics
{
    public class Technique
    {
        private Effect _effect;

        public Effect Effect
        {
            get { return _effect; }
            set
            {
                _effect = value;
                Parameters.Effect = _effect;
            }
        }
        [SerializableProperty("")]
        public string Name { get; set; }
        [SerializableIList]
        public ParameterBindingCollection Parameters { get; set; }

        public Technique()
        {
            Parameters = new ParameterBindingCollection();
        }

        public void Activate()
        {
            Effect.CurrentTechnique = Effect.Techniques[Name];
        }

        public void Load()
        {
            Parameters.Load();
        }

        public void SetParameter<T>(string parameter, T value)
        {            
            ParameterBinding b = Parameters.FirstOf(parameter);

            if (b != null)
            {
                Parameters[parameter].SetValue<T>(value);
            }
            else
            {
                EffectParameter p = Effect.Parameters[parameter];

                if (p != null)
                {
                    ParameterBinding binding = new ParameterBinding()
                    {
                        ID = parameter,
                        Parameter = parameter,
                        Effect = Effect,
                        Value = value,
                        IsDirty = true
                    };
                    Parameters.Add(binding);
                }
            }
        }

        public T GetParameter<T>(string parameter)
        {
            return Parameters[parameter].GetValue<T>();
        }

        public void LoadParameter(string parameter)
        {
            Parameters[parameter].SetParameter(true);
        }

        public void LoadContent()
        {
            Parameters.LoadContent();
        }
    }
}
